﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Write.API.Command.UserCommand;
using MediatR;

namespace B.S.BaseData.Write.API.CommandHandler.UserHandler
{
    public class AddUserHandler : IRequestHandler<AddUserCommand, APIResult<object>>
    {
        private readonly IBaseRepository<User> userRep;
        private readonly IMapper mapper;

        public AddUserHandler(IBaseRepository<User> userRep,IMapper mapper)
        {
            this.userRep = userRep;
            this.mapper = mapper;
        }
        public Task<APIResult<object>> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            var user = userRep.GetAll().Where(x=>x.Name==request.Name).Count();
            if (user<=0)
            {
                var a = mapper.Map<User>(request);
                var now = DateTime.Now;
                a.Pass = "123456";
                a.UpdateUser = "";
                a.CreateUser = "admin";
                a.CreateTime = now;
                a.UpdateUser = "";
                a.IsDeleted = false;

                var u = userRep.AddAsync(a).Result;
                
                    result.Code = APIEnum.Success;
                    result.Msg = "添加成功";
                    result.Data = u;

            }
            else
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "用户名重复，添加失败";

                }

          
            
            return Task.FromResult(result);
        }
    }
}
